package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
   @Autowired
   private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //日期计算
        List<LocalDate> dateList= new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);//获得指定日期后一天的日期
            dateList.add(begin);
        }
   //查询在日期范围内的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder().dateList(StringUtils.join(dateList,",")).turnoverList(StringUtils.join(turnoverList,",")).build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //计算日期
        List<LocalDate> dateList= new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //求日期内每天的总用户数量
        List<Integer> totalUserList = new ArrayList<>();
        //求日期内每日新增的用户数
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=date.atTime(LocalTime.MIN);
            LocalDateTime endTime=date.atTime(LocalTime.MAX);
            //计算每天新增用户数
            Integer newUserSum=userMapper.getUserCount(beginTime,endTime);
            //计算当天总用户数量
            Integer totalUserSum=userMapper.getUserCount(null,endTime);
            totalUserList.add(totalUserSum);
            newUserList.add(newUserSum);
        }

    return UserReportVO.builder().dateList(StringUtils.join(dateList,",")).
            totalUserList(StringUtils.join(totalUserList,",")).
            newUserList(StringUtils.join(newUserList,",")).build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //计算日期
        List<LocalDate> dateList= new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每日订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=date.atTime(LocalTime.MIN);
            LocalDateTime endTime=date.atTime(LocalTime.MAX);
            //计算每日订单数
            Integer ordercount=orderMapper.getOrderCount(beginTime,endTime,null);
            //计算每日有效订单数
            Integer validOrderCount=orderMapper.getOrderCount(beginTime,endTime,Orders.COMPLETED);
            orderCountList.add(ordercount);
            validOrderCountList.add(validOrderCount);
        }
        //计算订单总数
           Integer totalOrderCount=0;
           Integer validOrderCount=0;
        for (Integer i : orderCountList) {
            totalOrderCount+=i;
        }
        for (Integer i : validOrderCountList) {
            validOrderCount+=i;
        }
        Double orderCompletionRate= validOrderCount.doubleValue()/totalOrderCount;
        return OrderReportVO.builder().dateList(StringUtils.join(dateList,",")).
                orderCountList(StringUtils.join(orderCountList,",")).
                validOrderCountList(StringUtils.join(validOrderCountList,",")).
                totalOrderCount(totalOrderCount).
                 orderCompletionRate(orderCompletionRate).
                validOrderCount(validOrderCount).build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime=begin.atTime(LocalTime.MIN);
        LocalDateTime endTime=end.atTime(LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList=orderMapper.getSalesTop10(beginTime,endTime);
        List<Integer> numberList=new ArrayList<>();
        List<String> nameList=new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            numberList.add(goodsSalesDTO.getNumber());
            nameList.add(goodsSalesDTO.getName());
        }
        return SalesTop10ReportVO.builder().nameList(StringUtils.join(nameList,",")).numberList(StringUtils.join(numberList,",")).build();
    }
    /**导出近30天的运营数据报表
     * @param response
     **/
    @Override
    public void exprotBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessDataVO=workspaceService.getBusinessData(begin.atTime(LocalTime.MIN),end.atTime(LocalTime.MAX));
        //获取文件输入流
        InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于提供好的模板文件创建一个新的Excel表格对象
        try {
            XSSFWorkbook excel=new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet=excel.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin+"至"+end);
            //获得第四行
            XSSFRow row= sheet.getRow(3);
            //获取单元格并赋值
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第5行
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
           //准备明细数据
            for (int i = 0; i < 30; i++) {
            LocalDate date=begin.plusDays(i);
            BusinessDataVO businessDataVO1=workspaceService.getBusinessData(date.atTime(LocalTime.MIN),date.atTime(LocalTime.MAX));
            row=sheet.getRow(7+i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataVO1.getTurnover());
            row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO1.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out=response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
